package cn.matezk.lianlian.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.matezk.lianlian.dao.ApiPushDao;
import cn.matezk.lianlian.model.ApiPuh;
import cn.matezk.lianlian.service.IApiPushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApiPushService implements IApiPushService {
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ApiPushDao apiPushDao;

    @Override
    public void push(ApiPuh apiPuh) {
        try {
            taskExecutor.execute(() -> {
                HttpRequest request = new HttpRequest(apiPuh.getUrl()).method(Method.POST).body(apiPuh.getParams());
                apiPuh.setPushTime(new Date());
                HttpResponse response = request.execute();
                try {
                    apiPuh.setPushResult(response.getStatus());
                    apiPushDao.insertSelective(apiPuh);
                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {
                    response.close();
                }
            });
        } catch (Exception e) {
            apiPushDao.insertSelective(apiPuh);
        }
    }
}
